package com.lk.springboot.config;

import com.lk.springboot.service.ScheduleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author lk
 * @date 2020/1/20 0020 18:32
 */
@Component
public class ScheduleJob {
    private static final Logger logger = LoggerFactory.getLogger(ScheduleJob.class);
    //注入service对象 方便调用
    @Resource
    private ScheduleService scheduleService;

    @Scheduled(cron = "0 0 0 1/1 * ? ")   //每天执行一次
    public void clearDataJob() {
        logger.info("---------定时任务开始执行---------" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
        clearData(scheduleService);
        logger.info("---------定时任务执行成功---------" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
    }

    @Scheduled(cron = "0 0 0/12 * * ? ")   //每12h执行一次
    public void updateDataJob() {
        logger.info("---------定时任务2开始执行---------" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
        updateData(scheduleService);
        logger.info("---------定时任务2执行成功---------" + new SimpleDateFormat("HH:mm:ss").format(new Date()));
    }

    /**
     * 清理数据
     *
     * @param scheduleService
     */
    private static void clearData(ScheduleService scheduleService) {
        try {
            scheduleService.clearToken();//调用service层的方法 删除清空库数据
            scheduleService.resetSpeed();// 置空用户完成任务的进度
            scheduleService.resetMarketNum();// 将用户的魔法市场抽将次数 归零
            scheduleService.resetIsBought();// 将所有用户的魔法市场购买的拼图的记录，清零
            scheduleService.updateScoreExchange();// 每天更新积分兑换拼图的表
            scheduleService.resetTodayMileage();// 每天将今日里程数清零
        } catch (Exception e) {
            logger.error("清理数据失败，失败原因：" + e.getMessage());


        }
    }

    /**
     * 清理数据2
     *
     * @param scheduleService
     */
    private static void updateData(ScheduleService scheduleService) {
        try {
            scheduleService.resetMarketNum();// 将用户的魔法市场交易次数 归零
            scheduleService.resetIsBought();// 将所有用户的魔法市场购买的拼图的记录，清零
            scheduleService.addTodayMileage();// 定时更新里程相关任务
        } catch (Exception e) {
            logger.error("清理失败，失败原因：" + e.getMessage());
        }
    }
}